const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	let staff = await db.collection('staff').field({
		group_id: true,
		rule_code: true
	}).where({
		_openid: wxContext.OPENID,
		shop_id: event.shop_id,
	}).get()
	if (staff.data.length == 0) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	staff = staff.data[0]

	if (staff.group_id == 3 || (staff.group_id == 2 && !staff.rule_code)) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	let data = {
		name: event.name,
		price: event.price,
		is_show: event.is_show,
		code_id: event.code_id,
		to_home: event.to_home,
		to_shop:event.to_shop,
		shop_id:event.shop_id,
		update_time : new Date()
	}
	if (event._id) {
		let check = await db.collection('product').doc(event._id).field({
			shop_id: true
		}).get()
		if (check.data.shop_id != event.shop_id) {
			return {
				code: 20003,
				msg: '您无权进行此操作'
			}
		}
		let res = await db.collection('product').doc(event._id).update({
			data
		})
		if (res.errMsg == "document.update:ok")
			return {
				code: 200,
				msg: '保存成功',
				data: event._id
			}
	} else {
		data.create_time = data.update_time
		data.shop_id = event.shop_id
		let add = await db.collection('product').add({
			data
		})
		if (add.errMsg == 'collection.add:ok') {
			return {
				code: 200,
				msg: '保存成功',
				data: add._id
			}
		}
	}

	return {
		code: 20005,
		msg: '保存失败'
	}
}